package dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import util.HibernateUtil;
import vo.StrategicPerspectiveVO;
import entity.Organization;
import entity.StrategicPerspective;

public class StrategicPerspectiveDAO {
	
	public List<StrategicPerspectiveVO> listPerspectives(int idOrganization) {
		Session sessao = HibernateUtil.getSession();
		Criteria criterios = sessao.createCriteria(StrategicPerspective.class);
		
		if (idOrganization > 0)
			criterios.add(Restrictions.eq("organization.id", idOrganization));
		
		List<?> listaPerspective = criterios.list();
		List<StrategicPerspectiveVO> retorno = new ArrayList<StrategicPerspectiveVO>();
		for(Object obj:listaPerspective){
			StrategicPerspective sp = (StrategicPerspective) obj;
			StrategicPerspectiveVO spvo = new StrategicPerspectiveVO();
			
			spvo.setId(sp.getId());
			spvo.setName(sp.getName());
			spvo.setDescription(sp.getDescription());
			spvo.setAcronym(sp.getAcronym());
			spvo.setNameOrganization(sp.getOrganization().getName());
			spvo.setIdOrganization(sp.getOrganization().getId());
			
			retorno.add(spvo);
		}
		
		sessao.close();
		return retorno;
	}

	public int saveStrategicPerspective(StrategicPerspectiveVO spvo) {
		StrategicPerspective sp;
		
		Session sessao = HibernateUtil.getSession();
		
		if (spvo.getId() > 0){
			sp = (StrategicPerspective) sessao.load(StrategicPerspective.class, spvo.getId());
		}
		else{
			sp = new StrategicPerspective();
		}
		
		sp.setName(spvo.getName());
		sp.setDescription(spvo.getDescription());
		
		Criteria criterios = sessao.createCriteria(StrategicPerspective.class);
		criterios.add(Restrictions.eq("organization.id", spvo.getIdOrganization()));
		criterios.add(Restrictions.eq("acronym", spvo.getAcronym()));
		List<?> tmp = criterios.list();
		if (tmp.size() > 0){
			return -1;
		}
		
		sp.setAcronym(spvo.getAcronym());
		
		Organization o = (Organization) sessao.load(Organization.class, spvo.getIdOrganization());
		
		sp.setOrganization(o);
		
		Transaction tx = sessao.beginTransaction();
		
		try{			
			sessao.saveOrUpdate(sp);
			tx.commit();
			sessao.close();
			return sp.getId();
		}
		catch(Exception e){			
			e.printStackTrace();
			tx.rollback();
			sessao.close();
			
			return 0;
		}
	}

}
